package io.github.wanggit.antrpc.console.zookeeper;

import io.github.wanggit.antrpc.commons.bean.InterfaceNodeDataBean;
import io.github.wanggit.antrpc.commons.bean.RegisterBeanMethod;
import lombok.Data;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

@Data
public class InterfaceDTO implements Serializable {

    private static final long serialVersionUID = 4932052226308856680L;
    private String className;

    private String host;

    private Long registerTs;

    private String path;

    private String appName;

    private List<RegisterBeanMethod> interfaceMethodDTOS = new ArrayList<>();

    public static InterfaceDTO fromInterfaceNodeDataBean(InterfaceNodeDataBean it) {
        InterfaceDTO interfaceDTO = new InterfaceDTO();
        interfaceDTO.setRegisterTs(it.getTs());
        interfaceDTO.setPath(it.getFullPath());
        interfaceDTO.setHost(it.getHostInfo());
        interfaceDTO.setClassName(it.getClassName());
        interfaceDTO.setAppName(it.getAppName());
        List<RegisterBeanMethod> beanMethods = new ArrayList<>(it.getMethodMap().values());
        beanMethods.forEach(
                bm -> {
                    bm.generateMethodId();
                    bm.generateFullName();
                });
        interfaceDTO.setInterfaceMethodDTOS(
                beanMethods.stream()
                        .sorted(Comparator.comparing(RegisterBeanMethod::getHumanFullName))
                        .collect(Collectors.toList()));
        return interfaceDTO;
    }

    public InterfaceNodeDataBean toInterfaceNodeDataBean() {
        InterfaceNodeDataBean interfaceNodeDataBean = new InterfaceNodeDataBean();
        interfaceNodeDataBean.setAppName(getAppName());
        interfaceNodeDataBean.setHostInfo(getHost());
        interfaceNodeDataBean.setClassName(getClassName());
        interfaceNodeDataBean.setFullPath(getPath());
        Map<String, RegisterBeanMethod> methodMap =
                interfaceMethodDTOS.stream()
                        .collect(Collectors.toMap(RegisterBeanMethod::toString, it -> it));
        interfaceNodeDataBean.setMethodMap(methodMap);
        interfaceNodeDataBean.setMethods(new ArrayList<>(methodMap.keySet()));
        interfaceNodeDataBean.setTs(getRegisterTs());
        return interfaceNodeDataBean;
    }

    @Override
    public String toString() {
        return className + "@" + host + "[" + path + "]";
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof InterfaceDTO)) {
            return false;
        }
        InterfaceDTO other = (InterfaceDTO) obj;
        return Objects.equals(other.getClassName(), className)
                && Objects.equals(other.getHost(), host)
                && Objects.equals(other.getPath(), path);
    }

    @Override
    public int hashCode() {
        return className.hashCode() + host.hashCode() + path.hashCode();
    }
}
